package com.ruslan.magaz.web;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.ruslan.magaz.domain.Cart;
import com.ruslan.magaz.domain.Customer;
import com.ruslan.magaz.domain.Role;
import com.ruslan.magaz.domain.User;
import com.ruslan.magaz.service.UserService;

@Controller
@RequestMapping("/user")
public class UserController {
	
	@Autowired
	private UserService userService;
	
//	@ModelAttribute("users")
//	 public List<User> getAllUsers() {
//	  return userService.getAllUsers();
//	}
	
	static boolean isLoggedIn(HttpServletRequest req){
		HttpSession session = req.getSession(false);
		if (session == null){
			return false;
		}
		Object currentUserId = session.getAttribute("userId");
		if (currentUserId == null){
			return false;
		}
		return true;
	}
	
//	 @RequestMapping(value="login")
//	    public @ResponseBody
//		void logIn(HttpServletRequest req, HttpServletResponse res, @RequestParam("login") String login, @RequestParam("password") String password) throws ServletException, IOException{
//		        
//		        // TODO Auto-generated method stub
//		        //String login = @RequestParam("login") String login;
//		        //String pass = req.getParameter("pass");
//		        User thisUser = userService.login(login, password);
//		        if (thisUser != null){
//		            //HttpServletRequest httpReq = (HttpServletRequest) req;
//		            HttpSession session = req.getSession(true);
//		            session.setAttribute("userId", thisUser.getUserId());
//		            session.setAttribute("cart", new Cart());
//		            (res).setStatus(200);
//		        }else{
//		            (res).sendError(403);
//		        }
//		  }
	 
	 @RequestMapping(value="/userForm", method = RequestMethod.POST)
	    public String addUser(HttpServletRequest req, HttpServletResponse res, Model model, @Valid @ModelAttribute("user") User user, BindingResult bindingResult) throws ServletException, IOException{
				 if(bindingResult.hasErrors()){
					 return"tiles/userForm";
				 }
				 HttpSession session = req.getSession(true);
				 Object currentUserId = session.getAttribute("userId");
				 
		 		
		 		if (currentUserId == null) {
		 			Role role = userService.getRoleById(1);
			 		user.setRole(role);
		 			Customer newCustomer = new Customer();
		 			newCustomer.setUser(user);
		 			user.setCustomer(newCustomer);
		 			if (userService.getUserByName(user.getName()).size()>0){
		 				model.addAttribute("userExists", true);
		 				return"tiles/userForm";
		 			}
		 			if (userService.getUserByEmail(user.getEmail()).size()>0){
		 				model.addAttribute("emailExists", true);
		 				return"tiles/userForm";
		 			}
		 			try{
		 				userService.addUser(user);
		 			}catch(Exception e) {
		 				e.printStackTrace();
		 			}
		 			//HttpServletRequest httpReq = (HttpServletRequest) req;
		 			session.setAttribute("userId", user.getUserId());
		 			session.setAttribute("cart", new Cart());
		 		}else{
		 			
		 			user.setUserId((Integer)currentUserId);
					userService.editUser(user);
		 		}
//	            model.addAttribute("users", getAllUsers());
		 		if(user.getRole().getRoleId()==2){
		 			return "redirect:/admin";
		        }
	            return "redirect:/home";
		  }
	 
	 
	 @RequestMapping(value="/userForm", method = RequestMethod.GET)
	    public String registerUser(HttpServletRequest req, HttpServletResponse res, Model model) throws ServletException, IOException{
		 HttpSession session = req.getSession(true);
			if (!isLoggedIn(req)){
				User user = new User();
				Role role = userService.getRoleById(1);
		 		user.setRole(role);
		 		model.addAttribute("user", user);
			}else{
				int currentUserId = (Integer) session.getAttribute("userId");
		        User user = userService.getUserById(currentUserId);
		        if(user.getRole().getRoleId()==2){
		        	model.addAttribute("admin", true);
		        }
			    model.addAttribute("user", user);
			}
			return "tiles/userForm";
		  }

}
